package com.prathiba.tictactoe;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TicTacToeController {

	@RequestMapping(value = { "/**/tictac.c" })
	public ModelAndView tictac(@RequestParam("userId") int user,
			@RequestParam("coid") int coordinateId, HttpSession session) {
		ModelAndView mav = new ModelAndView("hi");
		Game game = (Game) session.getAttribute("game");
		Coordinate coordinate = Coordinate.value(coordinateId);
		if (game.doesListContainCoordinate(coordinate)) {
			mav.addObject("message", "Click another square");
			mav.addObject("coordinateValid", false);
			mav.addObject("endOfGame", false);

		} else {
			game.addCoordinate(user, coordinate);
			mav.addObject("coordinateValid", true);
			mav.addObject("endOfGame", false);

		}

		boolean won = game.gameWon();
		if (won) {
			mav.addObject("message", "Player " + user + " has won");
			mav.addObject("endOfGame", true);

		}

		boolean draw = game.gameDraw();
		if (draw) {
			mav.addObject("message", "Game is draw");
			mav.addObject("endOfGame", true);

		}

		return mav;
	}

	@RequestMapping(value = { "/**/startgame.c" })
	public void startGame(HttpSession session) {
		session.setAttribute("game", new Game());
	}

}